package handler;

import controller.Dispatcher;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import protocol.Request;
import service.Result;
import util.JsonUtil;

/**
 * @author yuzk
 * @date 2018/1/15
 */
public class HttpHandler extends SimpleChannelInboundHandler {

    Logger logger = LoggerFactory.getLogger(HttpHandler.class);

//    private static HttpHandler httpHandler = new HttpHandler();
//    private HttpHandler(){
//
//    }
//
//    public static HttpHandler getHttpHandler() {
//        return httpHandler;
//    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        FullHttpRequest request = (FullHttpRequest) msg;
        Request myRequest = new Request(request);

        Result result = Dispatcher.dispatch(myRequest);

        ByteBuf responseContent = Unpooled.compositeBuffer().writeBytes(JsonUtil.serialize(result).getBytes());
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED, responseContent);

        //这里需要加上addListener监听channel执行是否已经全部完成，否则会死循环无法输出response
        ctx.writeAndFlush(response)
                .addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.debug("read complete =============================");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.debug("not active =====================");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.debug("unRegister ====================");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.debug(" ######################################## error : " + cause.toString());
    }
}
